# -*- coding: UTF-8 -*-

'''
Created on 2014年5月31日

@author: areshero
'''
import urllib2
import json
import datetime
from home.models import Ontology
import threading
import time
import ontologies


REST_URL = "http://data.bioontology.org"
API_KEY = "1b466c88-c956-4682-8319-5e01f905b4f4"


class AnnotateThread(threading.Thread):
    def __init__(self, beginIndex, endIndex, annotations):
        super(AnnotateThread, self).__init__()
        self.beginIndex = beginIndex
        self.endIndex = endIndex
        self.annotations = annotations
        self.annotator_list = []
        self.ontologoies = []


    def run(self):
        
        #processing get annotations
        annotates_lists = []
        self.annotator_list[:] = []
        self.ontologoies[:] = []
        starttime1 = datetime.datetime.now()
        for resultIndex in range(self.beginIndex, self.endIndex):
            # result = self.annotations[resultIndex]
            
            tag_detail = dict()
            
            try:
                class_details = self.get_json(self.annotations[resultIndex]["annotatedClass"]["links"]["self"]) 
            except:
                #print "class details get json fail, the fail link is : "
                #print self.annotations[resultIndex]["annotatedClass"]["links"]["self"]
                pass
            tag_detail["id_in_database"] = 0
            tag_detail["id_in_bioportal"] = class_details["@id"]
            tag_detail["tag_prefLabel"] = class_details["prefLabel"]
            tag_detail["ontology_link"] = class_details["links"]["ontology"]
            tag_detail["distance"] = "0"
            tag_detail["parent_tag_link"] = class_details["links"]["parents"]
            
            tag_detail["annotations"] = dict()
            for annotation in self.annotations[resultIndex]["annotations"]:
                tag_detail["annotations"]["from"] =  str(annotation["from"])
                tag_detail["annotations"]["to"] = str(annotation["to"])
                tag_detail["annotations"]["matchType"] = annotation["matchType"]
            
            annotates_lists.append(tag_detail)
            
            ontology_detail = self.get_json(class_details["links"]["ontology"])
            #ontology1, isCreated1 = Ontology.objects.get_or_create(virtual_id = ontology_detail["@id"], name = ontology_detail["name"])
            ontology_object = dict()
            ontology_object['virtual_id'] = ontology_detail["@id"]
            ontology_object['name'] = ontology_detail["name"]
            
            self.ontologoies.append(ontology_object)
            
            if len(self.annotations[resultIndex]["hierarchy"]) != 0:
                for annotation in self.annotations[resultIndex]["hierarchy"]:
                    tmp_tag_detail = dict()
                    try:
                        # get the parent
                        class_details = self.get_json(annotation["annotatedClass"]["links"]["self"])
                        ontology_detail2 = self.get_json(class_details["links"]["ontology"])
                        #ontology2, isCreated2= Ontology.objects.get_or_create(virtual_id = ontology_detail2["@id"], name = ontology_detail2["name"] )
                        ontology_object2 = dict()
                        ontology_object2['virtual_id'] = ontology_detail["@id"]
                        ontology_object2['name'] = ontology_detail["name"]
                        self.ontologoies.append(ontology_object2)
                        tmp_tag_detail["id_in_database"] = 0
                        tmp_tag_detail["id_in_bioportal"] = class_details["@id"]
                        tmp_tag_detail["tag_prefLabel"] = class_details["prefLabel"]
                        tmp_tag_detail["ontology_link"] = class_details["links"]["ontology"]
                        tmp_tag_detail["parent_tag_link"] = class_details["links"]["parents"]
                        tmp_tag_detail["distance"] = str(annotation["distance"])
                    except:
                        pass
                    
                    annotates_lists.append(tmp_tag_detail)
                  
        endtime1 = datetime.datetime.now()
        interval = (endtime1 - starttime1)
        self.annotator_list = annotates_lists
        return annotates_lists
    
    def get_json(self, url):
        opener = urllib2.build_opener()
        opener.addheaders = [('Authorization', 'apikey token=' + API_KEY)]
        #r = opener.open(url).read()
        #f = open('json.txt', 'w')
        #f.write(r)
        #print 'testing...'
        #print opener.open('http://data.bioontology.org/ontologies/TESTONTO/classes/http%3A%2F%2Fwww.owl-ontologies.com%2FOntology1394230494.owl%23truc').read()
        #print 'test over'
        return json.loads(opener.open(url).read())

def startGetAnnotationsFromAnnotator(figureLegend,ontology_ids):
    SummingThreadInstance = AnnotateThread(1,1,[])
    annotations = SummingThreadInstance.get_json(REST_URL + 
                                                 "/annotator?max_level=1&text=" + 
                                                 urllib2.quote(figureLegend) +
                                                 "&ontologies=" +
                                                 ontology_ids
                                                 
                                                 )
    #annotations = ontologies.go(figureLegend, ontology_ids)
    return annotations

def startGetAnnotationsFromAnnotatorWithMaxLevel(figureLegend,ontology_ids,max_level):
    SummingThreadInstance = AnnotateThread(1,1,[])
    annotations = SummingThreadInstance.get_json(REST_URL + 
                                                 "/annotator?max_level=1&text=" + 
                                                 urllib2.quote(figureLegend) +
                                                 "&ontologies=" +
                                                 ontology_ids
                                                 
                                                 )
    #annotations = ontologies.search(figureLegend, ontology_ids)
    return annotations

def startGetAnnotationsFromAnnotator1(figureLegend, threadParam):
    SummingThreadInstance = AnnotateThread(1, 1, [])
    annotations = SummingThreadInstance.get_json(REST_URL + 
                                                 "/annotator?max_level=1&text=" + 
                                                 urllib2.quote(figureLegend)
                                                 )

    index = 0
    thread_arr = []
    while index +threadParam < len(annotations):
        thread = AnnotateThread(index, index+threadParam, annotations)
        index = index +threadParam
        thread_arr.append(thread)
    thread1 = AnnotateThread(index, len(annotations), annotations)
    thread_arr.append(thread1)
    
    for i in thread_arr:
        i.start()
        time.sleep(2)
    for j in thread_arr:
        j.join()
        
    # At this point, both threads have completed
    annotate_result = []
    ontologies_result = []
    for x in thread_arr:
        annotate_result.extend(x.annotator_list)
        ontologies_result.extend(x.ontologoies)
    return annotate_result, ontologies_result
